package cn.tedu.qxhouserent.passport.service.impl;


import cn.tedu.qxhouserent.commons.ex.ServiceException;
import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.commons.util.PageInfoToPageDataConverter;
import cn.tedu.qxhouserent.passport.mapper.PermissionMapper;
import cn.tedu.qxhouserent.passport.mapper.RolePermissionMapper;
import cn.tedu.qxhouserent.passport.pojo.entity.Permission;
import cn.tedu.qxhouserent.passport.pojo.entity.RolePermission;
import cn.tedu.qxhouserent.passport.pojo.param.PermissionAddNewParam;
import cn.tedu.qxhouserent.passport.pojo.param.PermissionUpdateInfoParam;
import cn.tedu.qxhouserent.passport.pojo.vo.PermissionListItemVO;
import cn.tedu.qxhouserent.passport.pojo.vo.PermissionStandardVO;
import cn.tedu.qxhouserent.passport.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.tedu.qxhouserent.commons.web.ServiceCode.*;

@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;



    @Override
    public void addNew(PermissionAddNewParam permissionAddNewParam) {

        log.debug("开始处理【添加权限】的业务，参数：{}", permissionAddNewParam);
        // 检查权限名称是否被占用,如果被占用,则抛出异常
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",permissionAddNewParam.getName());//name='参数中的相册名称
        Integer countByName = permissionMapper.selectCount(queryWrapper);
        log.debug("根据权限名称统计匹配的权限数量，结果：{}", countByName);
        if (countByName > 0){
            String message = "添加权限失败,权限名称已经被占用!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        //  检查权限路径值是否被占用，如果被占用，则抛出异常
        QueryWrapper<Permission> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("value",permissionAddNewParam.getValue());
        Integer countByName2 = permissionMapper.selectCount(queryWrapper2);
        log.debug("根据权限路径值统计匹配的权限数量，结果：{}", countByName2);
        if (countByName2 > 0){
            String message = "添加权限失败,权限路径值已经被占用!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionAddNewParam,permission);
        permission.setGmtCreate(LocalDateTime.now());
        permission.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的权限数据写入到数据库，数据：{}", permission);

        int rows = permissionMapper.insert(permission);
        if (rows != 1) {
            String message = "添加权限失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ERR_INSERT, message);
        }
        log.debug("将新的权限数据写入到数据库，完成！");

        //插入角色权限关联表
//        Long[] roleIds = permissionAddNewParam.getRoleIds();
//        RolePermission[] rolePermissions = new RolePermission[roleIds.length];
//        LocalDateTime now = LocalDateTime.now();
//        for (int i = 0; i < rolePermissions.length; i++) {
//            RolePermission rolePermission = new RolePermission();
//            rolePermission.setPermissionId(permission.getId());
//            rolePermission.setRoleId(roleIds[i]);
//            rolePermission.setGmtCreate(now);
//            rolePermission.setGmtModified(now);
//            rolePermissions[i] = rolePermission;
//        }
//        rows = rolePermissionMapper.insertBatch(rolePermissions);
//        if (rows != rolePermissions.length) {
//            String message = "添加角色权限失败，服务器忙，请稍后再试！";
//            log.warn(message);
//            throw new ServiceException(ERR_INSERT, message);
//        }

//        log.debug("将新的权限与角色的关联数据插入到数据库,完成!");
    }

    @Override
    public void deleteById(Long id) {

        // 检查权限名称是否存在,如果不存在,则抛出异常
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Integer countById = permissionMapper.selectCount(queryWrapper);
        log.debug("根据权限ID统计匹配的权限数量，结果：{}", countById);
        if (countById == 0){
            String message = "删除权限失败,权限数据不存在";
            log.warn(message);
            throw new ServiceException(ERR_NOT_FOUND,message);
        }

        //删除权限表
        int rows = permissionMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除权限失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }

        //将原有role_permission关联删除
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("permission_id", id);
        Integer integer = rolePermissionMapper.selectCount(rolePermissionQueryWrapper);

        if (integer != 0) {
            int i1 = rolePermissionMapper.deleteByPermissionId(id);
            if (i1 != integer) {
                String message = "删除失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_DELETE, message);
            }
        }
    }

    @Override
    public void updateInfoById(Long id, PermissionUpdateInfoParam permissionUpdateInfoParam) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Integer countById = permissionMapper.selectCount(queryWrapper);
        log.debug("根据权限ID统计匹配的权限数量，结果：{}", countById);
        if (countById == 0){
            String message = "修改权限失败,权限数据不存在";
            log.warn(message);
            throw new ServiceException(ERR_NOT_FOUND,message);
        }

        QueryWrapper<Permission> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name",permissionUpdateInfoParam.getName())
                .ne("id",id);
        Integer countByName = permissionMapper.selectCount(queryWrapper2);
        log.debug("根据权限名称统计匹配的权限数量，结果：{}", countByName);
        if (countByName > 0){
            String message = "修改权限失败,权限名称已经被占用!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        QueryWrapper<Permission> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("value",permissionUpdateInfoParam.getValue())
                .ne("id",id);
        Integer countByName2 = permissionMapper.selectCount(queryWrapper3);
        log.debug("根据权限请求路径统计匹配的权限数量，结果：{}", countByName2);
        if (countByName2 > 0){
            String message = "修改权限失败,权限请求路径已经被占用!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionUpdateInfoParam,permission);
        permission.setId(id);
        permission.setGmtModified(LocalDateTime.now());

        int rows = permissionMapper.updateById(permission);
        if (rows != 1) {
            String message = "修改权限失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ERR_INSERT, message);
        }

        //将原有role_permission关联删除
//        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
//        rolePermissionQueryWrapper.eq("permission_id", id);
//        Integer integer = rolePermissionMapper.selectCount(rolePermissionQueryWrapper);
//
//        if (integer != 0) {
//            int i1 = rolePermissionMapper.deleteByPermissionId(id);
//            if (i1 != integer) {
//                String message = "删除失败，服务器忙，请稍后再试！";
//                log.warn(message);
//                throw new ServiceException(ERR_DELETE, message);
//            }
//        }

        //新增role_permission新关联
//        Long[] roleIds = permissionUpdateInfoParam.getRoleIds();
//        if (roleIds.length != 0) {
//            RolePermission[] rolePermissions = new RolePermission[roleIds.length];
//            for (int j = 0; j < roleIds.length; j++) {
//                RolePermission rolePermission = new RolePermission();
//                rolePermission.setPermissionId(id)
//                        .setRoleId(roleIds[j])
//                        .setGmtCreate(LocalDateTime.now())
//                        .setGmtModified(LocalDateTime.now());
//                rolePermissions[j] = rolePermission;
//            }
//            int i2 = rolePermissionMapper.insertBatch(rolePermissions);
//            if (i2 != rolePermissions.length) {
//                String message = "添加失败，服务器忙，请稍后再试！";
//                log.warn(message);
//                throw new ServiceException(ERR_INSERT, message);
//            }
//        }
    }

    @Override
    public PermissionStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询权限详情】的业务，参数：{}", id);
        PermissionStandardVO queryResult = permissionMapper.getStandardById(id);
        // AlbumStandardVO queryResult = albumRedisRepository.get(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询权限详情失败，权限数据不存在！";
            log.warn(message);
            throw new ServiceException(ERR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public PageData<PermissionListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<PermissionListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询权限列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<PermissionListItemVO> list = permissionMapper.list();
        PageInfo<PermissionListItemVO> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverter.convert(pageInfo);
    }
}
